from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.utils.timezone import utc

from common.models import Hosts, CpuRate, MemRate, DiskRate
from datetime import datetime,timedelta
import time,pytz,json,os

# Create your views here.
def utc_to_local(utc_time_str, utc_format='%Y-%m-%dT%H:%M:%S+00:00', local_format = '%H:%M:%S'):
    '''将UTC时间转化成北京时间'''
    local_tz = pytz.timezone('Asia/Shanghai')
    utc_dt = datetime.strptime(utc_time_str, utc_format)
    local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
    # print(local_dt)
    time_str = local_dt.strftime(local_format)
    return time_str

def index(request, hid):
    '''展示主机详情页，查看使用率信息'''
    try:
        #获取主机信息对象
        item = Hosts.objects.get(id=hid)
        context={"host":item}
        return render(request,"myadmin/hosts/usage.html",context)
    except Exception as err:
        print(err)
        context={"info":"没有找到要查看的信息！"}
        return render(request,"myadmin/info.html",context)

def cpu(request, hid):
    '''查看主机CPU使用率信息'''
    #获取主机信息对象
    item = Hosts.objects.get(id=hid)

    #按主机IP过滤
    crlist = CpuRate.objects.filter(ip=item.ip)
    #now = datetime.now()
    utcnow = datetime.utcnow().replace(tzinfo=utc)
    an_hour_ago = utcnow - timedelta(hours=1)
    #an_hour_ago = now + timedelta(hours=7)
    #取1小时内的CPU使用率
    crlist = crlist.filter(addtime__gte=an_hour_ago).order_by('addtime')

    #封装Json数据
    list = []
    for cr in crlist:
        list.append({'addtime':utc_to_local(cr.addtime.strftime("%Y-%m-%dT%H:%M:%S+00:00")), 'percent':cr.percent})
    return JsonResponse({'data':list})

def mem(request, hid):
    '''查看主机内存使用率信息'''
    #获取主机信息对象
    item = Hosts.objects.get(id=hid)

    #按主机IP过滤
    mrlist = MemRate.objects.filter(ip=item.ip)
    #now = datetime.now()
    utcnow = datetime.utcnow().replace(tzinfo=utc)
    an_hour_ago = utcnow - timedelta(hours=1)
    #an_hour_ago = now - timedelta(hours=1)
    #取1小时内的内存使用率
    mrlist = mrlist.filter(addtime__gte=an_hour_ago).order_by('addtime')

    #封装Json数据
    list = []
    for mr in mrlist:
        list.append({'addtime':utc_to_local(mr.addtime.strftime("%Y-%m-%dT%H:%M:%S+00:00")),'percent':mr.percent})
    return JsonResponse({'data':list})

def disk(request, hid):
    '''查看主机硬盘使用率信息'''
    #获取主机信息对象
    item = Hosts.objects.get(id=hid)

    #按主机IP过滤
    drlist = DiskRate.objects.filter(ip=item.ip)
    #now = datetime.now()
    utcnow = datetime.utcnow().replace(tzinfo=utc)
    an_hour_ago = utcnow - timedelta(hours=1)
    #an_hour_ago = now - timedelta(hours=1)
    #取1小时内的硬盘使用率
    drlist = drlist.filter(addtime__gte=an_hour_ago).order_by('addtime')

    #封装Json数据
    list = []
    for dr in drlist:
        list.append({'addtime':utc_to_local(dr.addtime.strftime("%Y-%m-%dT%H:%M:%S+00:00")),'percent':dr.percent})
    return JsonResponse({'data':list})
